package com.zhousb.deviceManager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhousb.deviceManager.mapper.KiClientMapper;
import com.zhousb.deviceManager.mapper.SysUserClientMapper;
import com.zhousb.deviceManager.model.entity.KiClient;
import com.zhousb.deviceManager.model.entity.SysUserClient;
import com.zhousb.deviceManager.service.ClientService;
import com.zhousb.deviceManager.utils.AuthUtils;
import com.zhousb.deviceManager.utils.IdGenerator;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ClientServiceImpl implements ClientService {
    @Resource
    private KiClientMapper kiClientMapper;
    @Resource
    private SysUserClientMapper sysUserClientMapper;
    @Resource
    private AuthUtils authUtils;

    @Override
    public List<KiClient> listClient(String keyword) {
        Long userId = authUtils.getUser().getUserId();
        LambdaQueryWrapper<SysUserClient> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserClient::getUserId, userId);
        List<SysUserClient> userClients = sysUserClientMapper.selectList(queryWrapper);
        if (userClients.isEmpty()) {
            return new ArrayList<>();
        }
        List<Long> clientIds = userClients.stream().map(SysUserClient::getClientId).toList();
        LambdaQueryWrapper<KiClient> clientQueryWrapper = new LambdaQueryWrapper<>();
        clientQueryWrapper.in(KiClient::getId, clientIds);
        return kiClientMapper.selectList(clientQueryWrapper);
    }

    @Override
    public boolean addClient(KiClient kiClient) {

        Long clientId = IdGenerator.nextId();
        kiClient.setId(clientId);
        kiClientMapper.insert(kiClient);

        SysUserClient sysUserClient = new SysUserClient();
        sysUserClient.setId(IdGenerator.nextId());
        sysUserClient.setUserId(authUtils.getUser().getUserId());
        sysUserClient.setClientId(clientId);
        sysUserClientMapper.insert(sysUserClient);
        return true;
    }

    @Override
    public boolean delete(String id) {
        LambdaQueryWrapper<SysUserClient> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserClient::getClientId,id);
        sysUserClientMapper.delete(queryWrapper);
        return kiClientMapper.deleteById(id) > 0;
    }
}
